package com.gjp.myapplication.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.Adapter;

import com.gjp.myapplication.R;
import com.gjp.myapplication.bean.ImageItem;
import com.gjp.myapplication.utils.ImageUtil;

import java.util.ArrayList;
import java.util.List;

public class PhotoAdapter extends Adapter<PhotoAdapter.PhotoHolder> {

    private List<ImageItem> mDatas;

    private OnItemClickListener mOnItemClickListener;

    public PhotoAdapter(List<ImageItem> list) {
        this.mDatas = list != null ? list : new ArrayList<ImageItem>();
    }

    @NonNull
    @Override
    public PhotoHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.photo_item, parent, false);
        return new PhotoHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PhotoHolder holder, final int position) {
        holder.displayImage(mDatas.get(position));
        holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onClick(v, position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mDatas != null ? mDatas.size() : 0;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public interface OnItemClickListener {
        void onClick(View v, int position);
    }

    static class PhotoHolder extends RecyclerView.ViewHolder {

        ImageView imageView;
        TextView textView;

        private PhotoHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.iv);
            textView = itemView.findViewById(R.id.tv);
        }

        private void displayImage(ImageItem item) {
            ImageUtil.loadImage(item.getUrl(), imageView);
            textView.setText(item.getName());
//            Glide.with(imageView).load(url).into(imageView);
        }

    }

}